﻿'
'   APIHelperUtils.vb
'
'   part of WHMCSdotnet (http://whmcsdotnet.wordpress.com)
'
'   Copyright (C) 2009-2011 Mark Castle <markcastle@gmail.com>
'   All rights reserved. 
'   Copyright (C) 2009-2011 Secura Hosting Ltd <code@securahosting.com>.
'   All rights reserved.
' 
'   Redistribution and use in source and binary forms, with or without modification,
'   are permitted provided that the following conditions are met:
' 
'   - Redistributions of source code must  retain  the  above copyright notice, this
'     list of conditions and the following disclaimer.
' 
'   - Redistributions in binary form  must  reproduce the  above  copyright  notice,
'     this list of conditions  and  the  following  disclaimer in  the documentation
'     and/or other materials provided with the distribution.
' 
'   - Neither  the  name  of  Secura Hosting Ltd, Mark Castle  nor the names of  its
'     contributors may be used to endorse or  promote  products  derived  from  this
'     software without specific prior written permission.
' 
'   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
'   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,  BUT  NOT  LIMITED TO, THE IMPLIED
'   WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR  PURPOSE  ARE
'   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
'   ANY DIRECT, INDIRECT, INCIDENTAL,  SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL DAMAGES
'   (INCLUDING, BUT NOT LIMITED TO,  PROCUREMENT  OF  SUBSTITUTE  GOODS OR SERVICES;
'   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)  HOWEVER  CAUSED AND ON
'   ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT  LIABILITY,  OR TORT
'   (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING  IN  ANY WAY OUT OF THE USE OF THIS
'   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports Microsoft.VisualBasic
Imports System.IO


Namespace Secura.WHMCS
    ''' <summary>
    ''' Misc Help Functions
    ''' </summary>
    ''' <remarks></remarks>
    Public Class APIHelperUtils
        ''' <summary>
        ''' Read a Text File
        ''' </summary>
        ''' <param name="FullPath"></param>
        ''' <param name="ErrInfo"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetFileContents(ByVal FullPath As String, _
                                                Optional ByRef ErrInfo As String = "") As String

            Dim FileContents As String = ""
            Dim ReaderObj As StreamReader
            Try
                ReaderObj = New StreamReader(FullPath)
                FileContents = ReaderObj.ReadToEnd()
                ReaderObj.Close()
                Return FileContents
            Catch Ex As Exception
                ErrInfo = Ex.Message
                Return ""
            End Try
        End Function

        ''' <summary>
        ''' Base 64 Encode an Array of Strings
        ''' </summary>
        ''' <param name="TextArray"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Base64Encode(ByVal TextArray As String) As String
            Dim f As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
            Dim ms As New System.IO.MemoryStream()
            f.Serialize(ms, TextArray)
            Dim byArr As Byte() = ms.ToArray()
            Return Convert.ToBase64String(byArr)
        End Function

        ''' <summary>
        ''' Base 64 Encode a String
        ''' </summary>
        ''' <param name="TextToEncode"></param>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Shared Function EncodeTo64(ByVal TextToEncode As String) As String
            Dim toEncodeAsBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToEncode)
            Dim returnValue As String = System.Convert.ToBase64String(toEncodeAsBytes)
            Return returnValue
        End Function

        ''' <summary>
        ''' Decode a Base64 String
        ''' </summary>
        ''' <param name="EncodedData"></param>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Shared Function DecodeFrom64(ByVal EncodedData As String) As String
            Dim encodedDataAsBytes As Byte() = System.Convert.FromBase64String(EncodedData)
            Dim returnValue As String = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes)
            Return returnValue
        End Function

        ''' <summary>
        ''' Build a PHP Style Associative Array Structure (Serialised as Text)
        ''' </summary>
        ''' <param name="nvCol"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function BuildPhpArray(ByVal nvCol As System.Collections.Specialized.NameValueCollection) As String
            ' a:<<size>>:{<<keytype>>:<<key>>;<<valuetype>>:<<value>>;...}
            ' Example: a:3:{i:0;s:14:"sh20110915-001";i:1;s:7:"testing";i:2;s:6:"Test 2";}
            Dim Items As Integer = nvCol.Count
            If Items < 0 Then
                Return "NO DATA"
                Exit Function
            End If
            Dim PhpArr As String = ""
            PhpArr &= "a:" & Items & ":{"
            For i As Integer = 0 To nvCol.Count - 1
                If IsNumeric(nvCol.Keys(i).ToString()) Then
                    PhpArr &= "i:" & nvCol.Keys(i).ToString() & ";"
                Else
                    PhpArr &= "s:" & nvCol.Keys(i).Length.ToString() & ":""" & nvCol.Keys(i).ToString() & """;"
                End If

                PhpArr &= "s:" & nvCol.Item(i).Length.ToString() & ":""" & nvCol.Item(i).ToString() & """;"
            Next
            PhpArr &= "}"
            Return PhpArr
        End Function

        ''' <summary>
        ''' Converts a Name Value Collection into a Base64 Encoded Serialized PHP associative Array required by WHMCS (for CustomFields)
        ''' </summary>
        ''' <param name="nvCol"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetBase64SerializedArray(ByVal nvCol As System.Collections.Specialized.NameValueCollection) As String
            Return EncodeTo64(BuildPhpArray(nvCol))
        End Function

        ''' <summary>
        ''' Convert Country in Full Name ISO Format to 2 Letter ISO Format
        ''' </summary>
        ''' <param name="name"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function ConvertCountryToTwoLetterName(ByVal name As String) As String
            If name.Length = 0 Then
                Throw New ArgumentException("country name missing")
            End If

            name = name.ToUpper()

            Dim cultures As System.Globalization.CultureInfo() = _
                System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.SpecificCultures)
            For Each culture As System.Globalization.CultureInfo In cultures
                Dim region As New System.Globalization.RegionInfo(culture.LCID)
                If region.EnglishName.ToUpper() = name Then
                    Return region.TwoLetterISORegionName
                End If
            Next

            Return ""
        End Function

    End Class
End Namespace
